package faceattendsystem.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import faceattendsystem.entity.Daytime;
import faceattendsystem.entity.Mechanism;
import faceattendsystem.service.IDaytimeService;
import faceattendsystem.serviceImpl.DaytimeServiceImpl;
import net.sf.json.JSONObject;

public class AddDaytimeServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		IDaytimeService daytimeService = new DaytimeServiceImpl();
		
		Map<String,String> errors = new HashMap<String,String>();
		String mechid = req.getParameter("mechid");
		String daytype = req.getParameter("daytype");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String daybdate = req.getParameter("daybdate");
		String dayedate = req.getParameter("dayedate");
		
		if(daybdate.compareTo(dayedate)>0){
			errors.put("dayedate", "结束日期不能比开始日期早!");
		}
		
		Date bdate = null,edate = null;
		try {
			bdate = new Date(sdf.parse(daybdate).getTime());
		} catch (ParseException e) {
			errors.put("daybdate", "开始日期错误!");
			//System.out.println("开始日期错误!");
			//e.printStackTrace();
		}
		
		Daytime daytime = new Daytime();
		Mechanism mechanism = new Mechanism();
		mechanism.setMechid(mechid);
		daytime.setMechanism(mechanism);
		daytime.setDaybdate(bdate);
		daytime.setDaytype(daytype);
		int result = daytimeService.isRepeatDate(daytime);
		if(result!=0){
			errors.put("daybdate", "日期已被覆盖!");
		}
		
		try {
			edate = new Date(sdf.parse(dayedate).getTime());
		} catch (ParseException e) {
			errors.put("dayedate", "结束日期错误!");
//			System.out.println("结束日期错误!");
//			e.printStackTrace();
		}
		
		String begintime = req.getParameter("begintime");
		String endtime = req.getParameter("endtime");
		if(begintime.compareTo(endtime)>0){
			errors.put("endtime", "下班不能比上班时间早!");
			//System.out.println(begintime+" "+endtime);
		}
		
		if(errors.size()!=0){
			errors.put("flag", "1");
		}else{
			errors.put("flag", "0");
			daytime.setDaybdate(bdate);
			daytime.setDayedate(edate);
			daytime.setBegintime(begintime.replace(":", ""));
			daytime.setEndtime(endtime.replace(":", ""));
			daytimeService.add(daytime);
		}
		JSONObject json = JSONObject.fromObject(errors);// 使用JSONobject将map对象转换成json对象
		PrintWriter out = resp.getWriter();
		out.print(json);
	}
}
